package com.safe.first.infrastructure.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.safe.first.common.model.R;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Mickey
 * @since 2022/6/12
 **/
@Component
@RequiredArgsConstructor
public class MySimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private final ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        response.setHeader("Content-Type", "application/json");
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        PrintWriter writer;
        writer = response.getWriter();
        writer.write(objectMapper.writeValueAsString(R.ofError(exception.getMessage())));
    }

}
